package com.difsonapps.android.joinme;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import java.util.Map.Entry;

import com.difsonapps.android.joinme.db.Contact;
import com.difsonapps.android.joinme.db.DataBaseViewMapHistory;
import com.difsonapps.android.joinme.db.DatabaseHandler;
import com.difsonapps.android.joinme.db.ViewMapHistoryTable;
import com.difsonapps.android.joinme.util.Utils;

import android.app.Fragment;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.AdapterView.OnItemClickListener;

public class ViewMapHistoryFragment extends Fragment {

	SimpleCursorAdapter mAdapter;
	MatrixCursor mMatrixCursor;	
	View rootView;
	DataBaseViewMapHistory dbMapHistory;
	DatabaseHandler dbContact;
	public ListView lstHistory;
	Map<String,ViewMapHistoryTable> mapOfHistoryDb;
	//Map<String, Contact> mapOfAllContacts;
	TreeMap<Integer, Object> sections = new TreeMap<Integer, Object>();
	// This is the select criteria
	//static final String SELECTION = "((" + ContactsContract.Data.DISPLAY_NAME+ " NOTNULL) AND (" + ContactsContract.Data.DISPLAY_NAME+ " != '' ) AND (" +ContactsContract.CommonDataKinds.Phone.HAS_PHONE_NUMBER+ " > 0))";
	private final String TAG = this.getClass().getSimpleName();
	
	  ListViewHistoryLoader listViewHistoryLoader= null;
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		if(rootView!=null)
			return rootView;
		if(dbMapHistory==null)
		{
			dbMapHistory = new DataBaseViewMapHistory(this.getActivity().getApplicationContext());
		}
		mapOfHistoryDb = dbMapHistory.getMapHistory();
		
		
		if(dbContact==null)
		{
			dbContact = new DatabaseHandler(this.getActivity().getApplicationContext());
		}
		//mapOfAllContacts = dbHandler.getMapContacts();
		
		Log.e(TAG, "[onCreateView]");
		 rootView = inflater.inflate(R.layout.fragment_view_map_history, container,
				false);
	     // The contacts from the contacts content provider is stored in this cursor
        mMatrixCursor = new MatrixCursor(new String[] { "_id","photo","name","date","status"} );
        
        // Adapter to set data in the listview
        mAdapter = new SimpleCursorAdapter(getActivity().getBaseContext(),
                R.layout.history_list,
                mMatrixCursor,
                new String[] { "photo","name","date","status"},
                new int[] { R.id.history_tv_photo,R.id.history_tv_name,R.id.history_tv_date,R.id.history_tv_status}, 0);
        
        	// Getting reference to listview
        	lstHistory = (ListView) rootView.findViewById(R.id.lst_view_map_history);
            
//        	lstHistory.setOnItemClickListener(new OnItemClickListener(){
//            	
//            	public void onItemClick(AdapterView<?> parent, View view, int position, long arg3) 
//                {
//                    Cursor cur = (Cursor) mAdapter.getItem(position);
//                    cur.moveToPosition(position);
//                    String id = cur.getString(cur.getColumnIndexOrThrow("_id"));
//
//                    Intent intent = new Intent(getActivity(), ContactDetailActivity.class);
//                    Bundle bundle = new Bundle();
//                    bundle.putString ("id", id);
//                    intent.putExtras(bundle);
//
//                    startActivity(intent);
//                }
//            });
            	   
       
        // Setting the adapter to listview
        	lstHistory.setAdapter(mAdapter); 
        //lstContacts.setDivider(getResources().getDrawable(R.drawable.list_divider));
        
//     
//        	lstHistory.post(new Runnable() {
//        	    @Override
//        	    public void run() {
//        	    	
//        	    }
//        	});
        
        // Creating an AsyncTask object to retrieve and load listview with contacts
        	listViewHistoryLoader = new ListViewHistoryLoader();
        
        // Starting the AsyncTask process to retrieve and load listview with contacts
        	listViewHistoryLoader.execute();     
        
	 	
		return rootView;
	}
	
  	public void Update(long id){
  		
        // Creating an AsyncTask object to retrieve and load listview with contacts
  		ItemViewHistoryLoader itemViewHistoryLoader = new ItemViewHistoryLoader();
    
    // Starting the AsyncTask process to retrieve and load listview with contacts
  		itemViewHistoryLoader.execute((int) id);  
 		
  	}
  	
		
	    private class ItemViewHistoryLoader extends AsyncTask<Integer, Void, Cursor>{   	

	  		@Override
	  		protected Cursor doInBackground(Integer... params) {
	  			ViewMapHistoryTable Historyitem = dbMapHistory.getContactViewMap((int) params[0]) ;			
	  			Uri dataUri = ContactsContract.Data.CONTENT_URI;
	  				
	  				long contactId = Historyitem.getContactId();  	
	  				Date date = Historyitem.getDate();
	  				Cursor dataCursor = getActivity().getContentResolver().query(dataUri, null, 
	  						ContactsContract.Data.CONTACT_ID + "=" + contactId, 
	  						null, null);
	  				laoadUser(dataCursor,contactId,date);	  			
	  			return mMatrixCursor;
	  		}
	    }
  	
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
	   	Log.e(TAG, "[onCreate]");
		setRetainInstance(true);
		}
	
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	   	Log.e(TAG, "[onDestroy]");
//		if(listViewHistoryLoader!=null)
//		{
//			listViewHistoryLoader.cancel(true);
//		}
		}
	
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }   
    
    
    
    private class ListViewHistoryLoader extends AsyncTask<Void, Void, Cursor>{   	

  		@Override
  		protected Cursor doInBackground(Void... params) {
  			List<ViewMapHistoryTable> Historylist = dbMapHistory.getAllHistory() ;			
  			Uri dataUri = ContactsContract.Data.CONTENT_URI;
  			for(int i=0 ; i< Historylist.size(); i++){
  				long contactId = Historylist.get(i).getContactId();  
  				Date date = Historylist.get(i).getDate();
  				Cursor dataCursor = getActivity().getContentResolver().query(dataUri, null, 
  						ContactsContract.Data.CONTACT_ID + "=" + contactId, 
  						null, null);
  				laoadUser(dataCursor,contactId,date);

  			}
  			
  			return mMatrixCursor;
  		}
  		
  		
		
  	  	/*	@Override
  	  		protected void onPostExecute(Cursor result) {			
  	  			// Setting the cursor containing contacts to listview
  	  			mAdapter.swapCursor(result);
  	  		}	*/
  	  		
  	  		@Override
  	  		public void onPreExecute() {	
  	  			lockScreenOrientation();
  	  		}
  	  		
  	  		@Override
  	  		public void onPostExecute(Cursor result) {	
  	  
  	  			unLockScreenOrientation();
  	  		}
  	  		private void lockScreenOrientation()
  	  		{
  	  			
  	  			int currentOrientation = getResources().getConfiguration().orientation;
  	  			if(currentOrientation==Configuration.ORIENTATION_PORTRAIT)
  	  			{
  	  				getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  	  			}
  	  			else{
  	  				getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
  	  			}
  	  		}
  	      

  			private void unLockScreenOrientation()
  			{
  			
  					getActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);

  			}
  			
			
    }
    
    
	    protected void laoadUser(Cursor dataCursor,long id,Date date) {
				
			List<Entry<String, Integer>> phones = new ArrayList<Entry<String, Integer>>();
			List<Entry<String, Integer>> emails = new  ArrayList<Entry<String, Integer>>();
			String displayName="";
			String nickName="";

			String photoPath="" + R.drawable.ic_default_person_min;
			byte[] photoByte=null;

			String companyName="";
			String title="";
			String status=getString(R.string.invite).toUpperCase( Locale.getDefault());
			
			
			
			if(dataCursor.moveToFirst()){
				// Getting Display Name
				displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
				do{
										
//					// Getting NickName
//					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
//						nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
//					
//					// Getting Phone numbers
//					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
//						Map<String , Integer> map = new HashMap<String, Integer>();
//						map.put(dataCursor.getString(dataCursor.getColumnIndex("data1")), 1);
//						phones.add(map.entrySet().iterator().next());
//					}
//					
//					// Getting EMails
//					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ) ) {									
//						Map<String , Integer> map = new HashMap<String, Integer>();
//						map.put(dataCursor.getString(dataCursor.getColumnIndex("data1")), 1);
//						emails.add(map.entrySet().iterator().next());
//					}
//					
//					// Getting Organization details
//					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
//						companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
//						title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
//					}
						
					// Getting Photo	
					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){								
						photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
						
						if(photoByte != null) {							
							Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
							
							// Getting Caching directory 
		                    File cacheDirectory = getActivity().getBaseContext().getCacheDir();

		                    // Temporary file to store the contact image 
		                    File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+id+".png");

		                    // The FileOutputStream to the temporary file
		                    try {
								FileOutputStream fOutStream = new FileOutputStream(tmpFile);
								
								// Writing the bitmap to the temporary file as png file
			                    bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

			                    // Flush the FileOutputStream
			                    fOutStream.flush();

			                    //Close the FileOutputStream
			                    fOutStream.close();

							} catch (Exception e) {
								e.printStackTrace();
							}

		                    photoPath = tmpFile.getPath();
		                    if(photoPath ==null){
		                    	photoPath = "" + R.drawable.ic_default_person_min;
		                    }
						}
						
					}
					
				}while(dataCursor.moveToNext());					
				
				
				getActivity().getActionBar()
		        .setTitle(displayName);
				
				// Concatenating various information to single string
				
				
				status=getString(R.string.join_map);


				// Adding id, display name, path to photo and other details to cursor
				
				
			}
					
				final Object[] object = new Object[]{ Long.toString(id),photoPath,displayName,Utils.dateToString(date),status};
				getActivity().runOnUiThread(new Runnable() {
				public void run() {
					
					mMatrixCursor.addRow(object);
					mAdapter.swapCursor(mMatrixCursor);
					mAdapter.notifyDataSetChanged();
				
				}
			});
			
		}
    

     
  		
}
